package guoanmaker.operator.business.service;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CountDownLatch;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import ch.qos.logback.core.net.SyslogOutputStream;
import guoanmaker.operator.business.dao.LuckdrawRecordAndCouponsDao;
import guoanmaker.operator.business.model.OperatorActiveChance;
import guoanmaker.operator.business.model.OperatorCoupons;
import guoanmaker.operator.business.model.OperatorEventDetails;
import guoanmaker.operator.business.model.OperatorLuckdraw;
import guoanmaker.operator.business.model.OperatorLuckdrawRecord;
import guoanmaker.operator.business.model.PersonalUser;
import guoanmaker.operator.business.model.PersonalUserCoupon;
import guoanmaker.operator.business.modelnobind.LuckdrawRecordAndCoupons;
import guoanmaker.operator.business.modelnobind.OperatorLuckdrawAndDetails;
import guoanmaker.operator.business.repository.OperatorActiveChanceRepository;
import guoanmaker.operator.business.repository.OperatorCouponsRepository;
import guoanmaker.operator.business.repository.OperatorEventDetailsRepository;
import guoanmaker.operator.business.repository.OperatorLuckdrawRecordRepository;
import guoanmaker.operator.business.repository.OperatorLuckdrawRepository;
import guoanmaker.operator.business.repository.PersonalUserCouponRepository;
import guoanmaker.operator.business.repository.PersonalUserRepository;
import guoanmaker.operator.helper.common.AjaxJson;

@Service
public class OperatorLuckdrawService implements OperatorLuckdrawServiceInterface {
	private final OperatorLuckdrawRepository operatorLuckdrawRepository;
	private final OperatorLuckdrawRecordRepository operatorLuckdrawRecordRepository;
	private final OperatorEventDetailsRepository operatorEventDetailsRepository;
	private final OperatorCouponsRepository operatorCouponsRepository;
	private final PersonalUserCouponRepository personalUserCouponRepository;
	private final LuckdrawRecordAndCouponsDao LuckdrawRecordAndCouponsdao;
	private final PersonalUserRepository personalUserRepository;
	private final OperatorActiveChanceRepository operatorActiveChanceRepository;
	@PersistenceContext
	private EntityManager manager;

	public OperatorLuckdrawService(OperatorLuckdrawRepository operatorLuckdrawRepository,
			OperatorLuckdrawRecordRepository operatorLuckdrawRecordRepository,
			OperatorEventDetailsRepository operatorEventDetailsRepository,
			OperatorCouponsRepository operatorCouponsRepository,
			PersonalUserCouponRepository personalUserCouponRepository,
			LuckdrawRecordAndCouponsDao LuckdrawRecordAndCouponsdao,PersonalUserRepository personalUserRepository,
			OperatorActiveChanceRepository operatorActiveChanceRepository) {
		this.operatorLuckdrawRepository = operatorLuckdrawRepository;
		this.operatorLuckdrawRecordRepository = operatorLuckdrawRecordRepository;
		this.operatorEventDetailsRepository = operatorEventDetailsRepository;
		this.operatorCouponsRepository = operatorCouponsRepository;
		this.personalUserCouponRepository = personalUserCouponRepository;
		this.LuckdrawRecordAndCouponsdao = LuckdrawRecordAndCouponsdao;
		this.personalUserRepository=personalUserRepository;
		this.operatorActiveChanceRepository=operatorActiveChanceRepository;
	}

	@Transactional
	@Override
	public OperatorLuckdraw saveOperatorLuckdraw(OperatorLuckdraw operatorLuckdraw) {
		operatorLuckdraw.setDrawnum(0);
		return operatorLuckdrawRepository.save(operatorLuckdraw);
	}
	/*public AjaxJson OperatorLuckdraw(){
		final CountDownLatch latch = new CountDownLatch(2);
	    
	    new Thread(){
	        @SuppressWarnings("unused")
			public void run() {
	            try {
	                System.out.println("子线程"+Thread.currentThread().getName()+"正在执行");
	               Thread.sleep(3000);
	               System.out.println("子线程"+Thread.currentThread().getName()+"执行完毕");
	               OperatorLuckdraw Luckdraw=new OperatorLuckdraw();
	               Luckdraw.setActivityId("8a9a218f602e8c9401602edefafc000e");
	               Luckdraw.setUserId("8ab3fd565f18f6a6015f19a6eca00026");
					getOperatorLuckdraw(Luckdraw);
	               latch.countDown();
	           } catch (InterruptedException e) {
	               e.printStackTrace();
	           }
	        };
	    }.start();
	    new Thread(){
	        @SuppressWarnings("unused")
			public void run() {
	            try {
	                System.out.println("子线程"+Thread.currentThread().getName()+"正在执行");
	                Thread.sleep(3000);
	                System.out.println("子线程"+Thread.currentThread().getName()+"执行完毕");
	                OperatorLuckdraw operatorLuckdraw=new OperatorLuckdraw();
	                operatorLuckdraw.setActivityId("8a9a218f602e8c9401602edefafc000e");
	                operatorLuckdraw.setUserId("8ab3fd565f18f6a6015f19a6eca00026");
						getOperatorLuckdraw(operatorLuckdraw);
	                latch.countDown();
	           } catch (InterruptedException e) {
	               e.printStackTrace();
	           }
	        };
	    }.start();
	    try {
	        System.out.println("等待2个子线程执行完毕...");
	       latch.await();
	       System.out.println("2个子线程已经执行完毕");
	       System.out.println("继续执行主线程");
	   } catch (InterruptedException e) {
	       e.printStackTrace();
	   }
	    AjaxJson ajaxJson = new AjaxJson();
		return  ajaxJson.setSuccess(false).setStatus(102).setMsg("抽奖次数达到上限").setData(null);
	}*/
	@Transactional
	@Override
	public AjaxJson getOperatorLuckdraw(OperatorLuckdraw operatorLuckdraw){
		OperatorLuckdraw luckdraw = new OperatorLuckdraw();
		AjaxJson ajaxJson = new AjaxJson();
		OperatorEventDetails operatorEventDetails = operatorEventDetailsRepository
				.findOne(operatorLuckdraw.getActivityId());
		Long startTime = operatorEventDetails.getEventStartTime().getTime();
		Long endTime = operatorEventDetails.getEventEndTime().getTime();
		String userId = operatorLuckdraw.getUserId();
		PersonalUser personalUser=personalUserRepository.findOne(userId);
			if(personalUser==null || personalUser.equals("")){
				return ajaxJson.setSuccess(false).setStatus(103).setMsg("账户无效").setData(null);	
			}
		String ActivityId = operatorLuckdraw.getActivityId();
		Date date = new Date();
		int drawNum = 0;
		try {
			drawNum = operatorLuckdrawRecordRepository.queryCountByUseridAndActivityId(userId, ActivityId);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		if (drawNum == 0) {
			operatorEventDetailsRepository.updateEnrollmentAdd(ActivityId);
		}
		if (startTime <= date.getTime() && date.getTime() <= endTime) {
			if (operatorEventDetails.getLuckDrawType() == 0) { //0 总共 1 每天 
				if (drawNum < operatorEventDetails.getLuckDrawNum()) {
					return ajaxJson.setSuccess(true).setStatus(200).setMsg("")
							.setData(this.choujiang(userId, ActivityId));
				}
				if (drawNum >= operatorEventDetails.getLuckDrawNum()) {
					return ajaxJson.setSuccess(false).setStatus(102).setMsg("抽奖次数达到上限").setData(null);
				}
			}
			if (operatorEventDetails.getLuckDrawType() == 1) {
				@SuppressWarnings("unused")
				Date timeOne = new Date();
				@SuppressWarnings("unused")
				Date timeTwo = new Date();
				long time = date.getTime();
				time = time + 86400000;
				java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd");
				try {
					timeOne = dateFormat.parse(dateFormat.format(date));
					timeTwo = dateFormat.parse(dateFormat.format(new Date(time)));
				} catch (ParseException e) {
					e.printStackTrace();
				}
				int count = 0;
				try {
					count = operatorLuckdrawRecordRepository.queryCountByUseridAndActivityIdAndTime(userId, ActivityId,
							timeOne, timeTwo);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if (count < operatorEventDetails.getLuckDrawNum()) {
					return ajaxJson.setSuccess(true).setStatus(200).setMsg("")
							.setData(this.choujiang(userId, ActivityId));
				}
				if (count >= operatorEventDetails.getLuckDrawNum()) {
					return ajaxJson.setSuccess(false).setStatus(102).setMsg("抽奖次数达到上限").setData(null);
				}
			}
			//下单抽奖
			if(operatorEventDetails.getLuckDrawType() == 2){
				OperatorActiveChance operatorActiveChance = null;
				try {
					operatorActiveChance = operatorActiveChanceRepository.queryActiveChanceByuserId(userId,ActivityId);
				} catch (Exception e) {
					e.printStackTrace();
				}
				if(operatorActiveChance != null && operatorActiveChance.getNumber() !=0){
					operatorActiveChanceRepository.updateActiveChance(userId, ActivityId);
					return ajaxJson.setSuccess(true).setStatus(200).setMsg("")
							.setData(this.choujiang(userId, ActivityId));
				}
				if (operatorActiveChance != null && operatorActiveChance.getNumber() ==0) {
					return ajaxJson.setSuccess(false).setStatus(102).setMsg("抽奖次数达到上限").setData(null);
				}
			}
		}
		return ajaxJson.setSuccess(false).setStatus(101).setMsg("与活动时间不符").setData(null);
	}

	@Transactional
	// 抽奖
	public OperatorLuckdraw choujiang(String userId, String ActivityId) {
		List<OperatorLuckdraw> listLuck = operatorLuckdrawRepository.queryOperatorLuckdrawByActivityId(ActivityId);
		List<Integer> proSection = new ArrayList<Integer>();
		proSection.add(0);
		int weinum = 0;
		int totalPro = 0;
		for (OperatorLuckdraw luckdraw : listLuck) {// 当前奖品总数量(有限制类型)
			if (luckdraw.getMaxDrawNum() != 0) {
				weinum += luckdraw.getMaxDrawNum() - luckdraw.getDrawnum();
			}
		}
		for (OperatorLuckdraw luckdraw : listLuck) {

			int num = 0;// 剩余数量
			if (luckdraw.getNumber() == 0 && weinum != 0) {// (有其他奖项情况下的未中奖数量)中奖数量无限制
															// ：通过当前概率 *
															// 当前奖品总数量=无限制等级奖品数量
				Double gailv = luckdraw.getProbability();
				num = (int) (weinum * gailv);
				if (num == 0) {
					num = 1;
				}

			}
			if (luckdraw.getNumber() == 0 && weinum == 0) {// (无其他奖项未中奖的)当所有中奖品完全兑换
															// 后 只剩 未中奖
				num = 1;
			}
			if (luckdraw.getNumber() != 0) {// 中奖数量有限制
				num = luckdraw.getMaxDrawNum() - luckdraw.getDrawnum();
			}
			// 每个概率区间为奖品概率乘以1000（把三位小数转换为整）再乘以剩余奖品数量
			totalPro += luckdraw.getProbability() * 1000 * (num);
			proSection.add(totalPro);
		}
		// 获取总的概率区间中的随机数
		Random random = new Random();
		int randomPro = random.nextInt(totalPro);
		// 判断取到的随机数在哪个奖品的概率区间中
		for (int i = 0, size = proSection.size(); i < size; i++) {
			if (randomPro >= proSection.get(i) && randomPro < proSection.get(i + 1)) {
				// System.out.println(randomPro);
				// 中奖返回名称
				String lunckName = listLuck.get(i).getPrizeName();
				;
				// 添加中奖记录
				OperatorLuckdrawRecord OperatorLuckdrawRecord = new OperatorLuckdrawRecord();
				// 是否有优惠券
				if (listLuck.get(i).getIsCoupons() == 0) {// 关联优惠券

					OperatorCoupons operatorCoupons = new OperatorCoupons();
					// 添加记录信息
					OperatorLuckdrawRecord.setCouponsId(listLuck.get(i).getCouponsId());
					// 变更 优惠券发送数量
					operatorCouponsRepository.updateBeensentByid(listLuck.get(i).getCouponsId());
					// 向用户下 添加 优惠券信息
					PersonalUserCoupon personalUserCoupon = new PersonalUserCoupon();

					personalUserCoupon.setIsUsed("0");
					personalUserCoupon.setOcId(listLuck.get(i).getCouponsId());
					personalUserCoupon.setUserId(userId);
					OperatorCoupons coupons=operatorCouponsRepository.getOne(listLuck.get(i).getCouponsId());
					if (coupons.getDatetype().equals("1") == true) {
						personalUserCoupon.setExpiredDate(coupons.getEndofdate());
					} else {
						Date expiredDate = new Date();
						Calendar ca = Calendar.getInstance();
						ca.add(Calendar.DATE, operatorCoupons.getValidityPeriod());// num为增加的天数，可以改变的
						expiredDate = ca.getTime();
						personalUserCoupon.setExpiredDate(expiredDate);
					}
					personalUserCoupon.setStart_date(new Date());
					personalUserCouponRepository.save(personalUserCoupon);
				}
				OperatorLuckdrawRecord.setActivityId(ActivityId);
				OperatorLuckdrawRecord.setLuckdrawId(listLuck.get(i).getId());
				OperatorLuckdrawRecord.setLuckdrawType(listLuck.get(i).getPrizeName());
				OperatorLuckdrawRecord.setUserId(userId);
				OperatorLuckdrawRecord.setRecordTime(new Date());
				operatorLuckdrawRecordRepository.save(OperatorLuckdrawRecord);

				// 更改中奖 数量
				operatorLuckdrawRepository.updateOperatorLuckdraw(listLuck.get(i).getId());

				// 查询中奖记录
				OperatorLuckdraw Luckdraw = new OperatorLuckdraw();
				List<LuckdrawRecordAndCoupons> recordList = LuckdrawRecordAndCouponsdao
						.queryLuckRecordAndCouponsDao(userId, ActivityId);
				Luckdraw.setRecordCouponsList(recordList);
				Luckdraw.setPrizeName(lunckName);
				Luckdraw.setPicUrl(listLuck.get(i).getPicUrl());
				return Luckdraw;
			}
		}
		return null;
	}
	@Transactional
	@Override
	public OperatorLuckdraw getLuckdrawListByActivityId(String id, String userId) {
		OperatorLuckdraw operatorLuckdraw = new OperatorLuckdraw();
		OperatorEventDetails operatorEventDetails = operatorEventDetailsRepository.findOne(id);
		if(userId==null || userId.equals("")==true){
			String sql = "SELECT DISTINCT(ol.prize_name), ol.pic_url, oed.event_pic_url,oed.event_infor FROM t_operator_luckdraw ol,t_operator_event_details oed WHERE ol.activity_id = oed.id AND ol.activity_id =:id ORDER BY ol.weight DESC";
			Query query = manager.createNativeQuery(sql, OperatorLuckdrawAndDetails.class);
			@SuppressWarnings("unchecked")
			List<OperatorLuckdrawAndDetails> enlist = (List<OperatorLuckdrawAndDetails>) query.setParameter("id", id)
					.getResultList();
			operatorLuckdraw.setDrawList(enlist);
			operatorLuckdraw.setSurplusNum(operatorEventDetails.getLuckDrawNum());
			return operatorLuckdraw;
		}
		if(userId!=null || userId.equals("")!=true){
			Integer num = operatorEventDetails.getLuckDrawNum();
			int count = 0;
			if (operatorEventDetails.getLuckDrawType() == 0) {
				try {
					count = operatorLuckdrawRecordRepository.queryCountByUseridAndActivityId(userId, id);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (operatorEventDetails.getLuckDrawType() == 1) {
				Date date = new Date();
				@SuppressWarnings("unused")
				Date timeOne = new Date();
				@SuppressWarnings("unused")
				Date timeTwo = new Date();
				long time = date.getTime();
				time = time + 86400000;
				java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd");
				try {
					timeOne = dateFormat.parse(dateFormat.format(date));
					timeTwo = dateFormat.parse(dateFormat.format(new Date(time)));
				} catch (ParseException e) {
					e.printStackTrace();
				}
				try {
					count = operatorLuckdrawRecordRepository.queryCountByUseridAndActivityIdAndTime(userId, id, timeOne,
							timeTwo);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			Integer surplusNum = num - count;
			if(operatorEventDetails.getLuckDrawType() == 2){//下单抽奖
				OperatorActiveChance operatorActiveChance = null;
				try {
					operatorActiveChance = operatorActiveChanceRepository.queryActiveChanceByuserId(userId,id);
				} catch (Exception e) {
					e.printStackTrace();
				}
				if(operatorActiveChance != null){
					surplusNum = operatorActiveChance.getNumber();
				}
				if(operatorActiveChance ==null){
					surplusNum=0;
				}
			}
			String sql = "SELECT DISTINCT(ol.prize_name), ol.pic_url, oed.event_pic_url,oed.event_infor FROM t_operator_luckdraw ol,t_operator_event_details oed WHERE ol.activity_id = oed.id AND ol.activity_id =:id ORDER BY ol.weight DESC";
			Query query = manager.createNativeQuery(sql, OperatorLuckdrawAndDetails.class);
			@SuppressWarnings("unchecked")
			List<OperatorLuckdrawAndDetails> enlist = (List<OperatorLuckdrawAndDetails>) query.setParameter("id", id)
					.getResultList();
			List<LuckdrawRecordAndCoupons> recordList = LuckdrawRecordAndCouponsdao.queryLuckRecordAndCouponsDao(userId,
					id);
			operatorLuckdraw.setSurplusNum(surplusNum);
			operatorLuckdraw.setDrawList(enlist);
			operatorLuckdraw.setRecordCouponsList(recordList);
			return operatorLuckdraw;
		}
		return null;
		
	}

}
